package cn.fzkj.ws.config;

import cn.fzkj.ws.SocketHandler;
import cn.fzkj.ws.WebSocketInterceptor;
import cn.fzkj.ws.component.WebSocketComponent;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*;

/**
 * @ author mr @ description @ since 2024/12/26
 */
@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
@ConditionalOnProperty(value = "platform.websocket", havingValue = "enable", matchIfMissing = true)
public class WebSocketAutoConfiguration {

    @Bean
    public WebSocketMessageBrokerConfigurer webSocketStompConfig() {
        return new WebSocketStompConfig();
    }

    @Bean
    public WebSocketConfigurer webSocketConfig() {
        return new WebSocketConfig();
    }

    /**
     * Web Socket Stomp 配置
     *
     * @author bdyl1
     * @date 2024/12/30
     */
    public static class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {

        @Override
        public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
            stompEndpointRegistry.addEndpoint("/ws/v1/platform").setAllowedOriginPatterns("*") // 解决跨域问题
                .withSockJS().setHeartbeatTime(10000);
        }

        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
            registry.enableSimpleBroker("/topic");
        }
    }

    /**
     * Web 套接字配置
     *
     * @author bdyl1
     * @date 2024/12/30
     */
    public class WebSocketConfig implements WebSocketConfigurer {

        /**
         * 注册 Web 套接字处理程序
         *
         * @param registry 注册表
         */
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(socketHandler(), "/ws/v1/platform").addInterceptors(new WebSocketInterceptor())
                .setAllowedOriginPatterns("*");
        }

    }

    /**
     * 套接字处理程序
     *
     * @return 套接字处理程序
     */
    @Bean
    public SocketHandler socketHandler() {
        return new SocketHandler();
    }

    /**
     * Web Socket 服务
     *
     * @param socketHandler 套接字处理程序
     * @return Web Socket 组件
     */
    @Bean
    public WebSocketComponent webSocketService(SocketHandler socketHandler) {
        return new WebSocketComponent(socketHandler);
    }

}
